package com.ecld.grpc.tool;

import com.ecld.grpc.server.GRpcServer;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ConnectionPoolUtils {

    private static final Logger logger = Logger.getLogger(GRpcServer.class.getName());
    private static ConnectionPoolUtils connectionPoolUtils;
    private ComboPooledDataSource dataSource;

    static{
        connectionPoolUtils = new ConnectionPoolUtils();
    }

    private ConnectionPoolUtils() {
        try {
            dataSource = new ComboPooledDataSource();
            Properties props = new Properties();
            InputStream in = new BufferedInputStream(new FileInputStream("conf/c3p0.properties"));
            props.load(in);
            dataSource.setDriverClass(props.getProperty("DriverClass"));
            dataSource.setJdbcUrl(props.getProperty("JdbcUrl"));
            dataSource.setUser(props.getProperty("User"));
            dataSource.setPassword(props.getProperty("Password"));
            dataSource.setMaxPoolSize(Integer.parseInt(props.getProperty("MaxPoolSize")));
            dataSource.setMinPoolSize(Integer.parseInt(props.getProperty("MinPoolSize")));
            dataSource.setInitialPoolSize(Integer.parseInt(props.getProperty("InitialPoolSize")));
            dataSource.setMaxStatements(Integer.parseInt(props.getProperty("MaxStatements")));
            dataSource.setMaxIdleTime(Integer.parseInt(props.getProperty("MaxIdleTime")));
        } catch (Exception e) {
            logger.log(Level.WARNING,"Load C3P0 Unsuccess: "+e.getMessage());
        }
    }

    public static ConnectionPoolUtils getInstance(){
        return connectionPoolUtils;
    }

    public Connection getConnection(){
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (Exception e) {
            logger.log(Level.WARNING,"Get Connection Unsuccess: "+e.getMessage());
        }
        return conn;
    }
}
